#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project:     python_framework
# @File:        u_config_ini.py
# @Author:      Fan GuiChuan
# @Date:        2024/7/4 16:03
# @Version:     Python3.7
# @Description: INI配置文件管理工具类
import configparser
from .u_path import PathManager


class IniConfigManager(object):
    __config = None

    @classmethod
    def get(cls, refresh=False):
        """
        获取配置信息
        :param refresh: 强制刷新配置
        :return:
        """
        if cls.__config is None or refresh:
            config_dir = PathManager.path_join(PathManager.get_root_path(), "config")
            config_file = PathManager.path_join(config_dir, "config.ini")
            config_parser = configparser.ConfigParser()
            config_parser.read(config_file, encoding="utf-8")

            ini_config = dict()
            for option in config_parser.sections():
                option_config = dict()
                for key in config_parser.options(option):
                    value = config_parser.get(option, key)
                    option_config[key] = value
                ini_config[option] = option_config
            cls.__config = ini_config
        return cls.__config

    @classmethod
    def get_section_config(cls, section_name: str, refresh=False):
        """
        获取指定配置Section内容
        :param section_name:
        :param refresh:
        :return:
        """
        section_config = cls.get(refresh)
        return section_config.get(section_name, dict())

    @classmethod
    def get_option_config(cls, section_name: str, option_name: str, **kwargs):
        refresh = kwargs.get("refresh", False)
        default = kwargs.get("default", None)
        section_config = cls.get_section_config(section_name, refresh)
        value = section_config.get(option_name, default)
        return value


if __name__ == '__main__':
    config = IniConfigManager.get()
    print(f"config: {config}")
    print(f"database_type: {IniConfigManager.get_option_config('database_config', 'database_type')}")
